/**
 * 
 */
package edu.sjtu.seda.experiment;

import java.util.concurrent.TimeUnit;

import edu.sjtu.seda.event.Event;
import edu.sjtu.seda.event.EventHandler;
import edu.sjtu.seda.log.LogService;
import edu.sjtu.seda.test.Message;
import edu.sjtu.seda.test.PrintMessage;
import edu.sjtu.seda.test.TransferMessage;
import edu.sjtu.seda.test.WriteToFile;

/**
 * @author john.zhu
 *
 */
public class SingleThreadPoolTest {
	
	protected static LogService log = new LogService(SingleThreadPoolTest.class);
	
	static class RunTest implements Runnable{
		private Event event;
		private EventHandler eventhandlers;
		
		public RunTest(Event event,EventHandler eventhandlers){
			this.event = event;
			this.eventhandlers = eventhandlers;
		}
		
		public void run(){
			eventhandlers.handle(event);
			log.info("event " + event.getUID() + " is running");
		}
	}
	
	static class TestThread1 implements Runnable {

		private int i = 0;
		
        private SingleThreadPool tp;
        
		
		public TestThread1(int i, SingleThreadPool tp){
			this.i = i;
			this.tp = tp;
		}
		
		@Override
		public void run() {
			Message m = new Message("Message "+i);
			log.info("event "+m.getUID()+" will start");
			tp.execute(new RunTest(m,new PrintMessage()));
			tp.execute(new RunTest(m,new WriteToFile()));
		}
	}
	
	static class TestThread2 implements Runnable {

		private int i = 0;

		private SingleThreadPool tp;

		public TestThread2(int i, SingleThreadPool tp) {
			this.i = i;
			this.tp = tp;
		}

		@Override
		public void run() {
			Message m = new Message("Message " + i);
			log.info("event " + m.getUID() + " will start");
			tp.execute(new RunTest(m, new TransferMessage()));
			tp.execute(new RunTest(m, new WriteToFile()));
		}
	}
	
	public static void main(String[]args){
		long startNano = System.nanoTime();
		SingleThreadPool tp = new SingleThreadPool(50);
		for (int i = 0; i < 1000; i++) {
			if(i%2==0){
				Thread t1 = new Thread(new TestThread1(i, tp));
				t1.start();
			}
			else{
				Thread t2 = new Thread(new TestThread2(i, tp));
				t2.start();
			}
		}
		
	}

}
